//
//  M_SearchPageVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/11.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_SearchPageVC: BaseViewControllerWithHeader {
    let userSearchList = M_SearchList()
    let hotSearchList = M_SearchList()
    let searchField = TextField()
    
    //专区列表
    let tableView = QuickTableView<ZoneCodeModel,M_ZoneCell>()
    var zoneAry = [ZoneCodeModel]()
    var curZone : ZoneCodeModel?
    let zoneSelBtn = Button()
    
    //补全部分值角
    let jiaoView = UIView()
    let jView = UIView()
    let jView1 = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        getZoneCode()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if searchField.text?.count ?? 0 > 0 {
            searchField.becomeFirstResponder()
        }
        if let z = curZone {
            self.onSelectCell(data: z)
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    func getZoneCode() {
        if let ary = LocalStorage.getAryToZone(forKey: ZoneCode105) {
            zoneAry = ary
            self.queryData()
            self.tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .top)
            self.onSelectCell(data: zoneAry[0])
        }
        else {
            let popup = PopupSureBox(title: "获取标识失败，请从新登录", sureText: "确定")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
            }
        }
    }
    
    func getSyssettingbase(callback: @escaping (Bool,[String:Any?]) -> Void) {
        API.formRequest(url: .YI_GetSyssettingbase, params: nil, callback: { (result) in
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    callback(result.success, dl)
                }
                else {
                    callback(result.success, [:])
                }
            }
        })
    }

    func getSearchHistory(page: Int, pageSize:Int) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "zoneCode":curZone?.code ?? "",
                                    "pageIndex":page,
                                    "pageSize":pageSize]
        API.request(url: .M_SearchHistory, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                   var ary = [String]()
                   for item in dl.getDictList("items") ?? [] {
                       if let keyword = item.getString("keyword"){
                           ary.append(keyword)
                       }
                   }
                   self.userSearchList.listAry = ary
               }
            }else{
            }
            
        }
    }
    
    func delSearchHistory() {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "zoneCode":curZone?.code ?? ""]
        API.request(url: .M_Del_SearchHistory, params: params) { (result) in
            if result.success {
                self.userSearchList.listAry = []
            }
            else {
                let popup = PopupSureBox(title: result.errMsg ?? "操作完成", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    self.getSearchHistory(page: 1, pageSize: 10)
                }
            }
        }
    }
    
    func getSearchHot(page: Int, pageSize:Int) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "zoneCode":curZone?.code ?? "",
                                    "pageIndex":page,
                                    "pageSize":pageSize]
        API.request(url: .M_SearchHot, params: params) { (result) in
            self.getSearchHistory(page: 1, pageSize: 10)
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                   var ary = [String]()
                   for item in dl.getDictList("items") ?? [] {
                       if let keyword = item.getString("keyword"){
                           ary.append(keyword)
                       }
                   }
                   self.hotSearchList.listAry = ary
               }
            }else{
            }
        }
    }
    
    func searchData(page: Int, pageSize:Int) {
        let dirZone = LocalStorage.getAryToZone(forKey: ZoneCode106)!
        let sortZone = LocalStorage.getAryToZone(forKey: ZoneCode117)!
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "keyword":searchField.text ?? "",
                                    "zoneCode":curZone?.code ?? "",
                                    "sort":sortZone[0].code ?? "",
                                    "dir":dirZone[0].code ?? "",
                                    "pageIndex":page,
                                    "pageSize":pageSize]
        MBProgressHUD.showOrIncrease()
        API.request(url: .M_SearchAction, params: params) { (result) in
            if result.success {
                
            }else{
                let popup = PopupSureBox(title: result.errMsg ?? "找不到商品", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
            MBProgressHUD.hideOrDecrease()
        }
    }
}

// MARK:- UI
extension M_SearchPageVC {
    func setupUI() {
        headView.snp.remakeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(safeView.snp.top).offset(64-20)
            make.top.equalToSuperview().offset(-44)
        }
        
        //        背景view
        let search_bgView = headView.drawView() { (make) in
            make.left.equalToSuperview().offset(33)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-8)
            make.height.equalTo(28)
        }
        // 设置边框
        search_bgView.layer.borderWidth = 1
        search_bgView.layer.borderColor = UIColor.xF2F2F2.cgColor
        search_bgView.backgroundColor = .white
        search_bgView.layer.cornerRadius = 7.0

        headView.drawView(view: jiaoView){ (make) in
            make.width.height.equalTo(10)
            make.left.bottom.equalTo(search_bgView)
        }
        jiaoView.backgroundColor = .white
        jiaoView.isHidden = true
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.SetBorderWithView(self.jiaoView,top: false,left: true,bottom: true,right: false,width: 1,color: UIColor.xF2F2F2)
        }
//        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//            search_bgView.layer.mask = self.configRectCorner(view: search_bgView, corner: [.topLeft,.topRight,.bottomRight], radii: CGSize(width: 7, height: 7))
//        }
        
        
        search_bgView.drawButton(button: zoneSelBtn,title: "自营", titleColor: .x666666, fontSize: 12) { (make) in
            make.top.equalToSuperview().offset(6)
            make.left.equalToSuperview().offset(10)
            make.width.equalTo(50)
        }
        zoneSelBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        zoneSelBtn.addTarget(self, action: #selector(onSelAction(button:)), for: .touchUpInside)
        
        search_bgView.drawImage(named: "lishixiangxia_60") { (make) in
            make.centerY.equalTo(zoneSelBtn.snp.centerY)
            make.left.equalTo(zoneSelBtn.snp.right)
        }
        
        let bview = search_bgView.drawView() { (make) in
            make.left.equalTo(zoneSelBtn.snp.right).offset(15)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
            make.width.equalToSuperview().offset(-125)
        }
        bview.backgroundColor = .xF2F2F2
        
        search_bgView.drawTextField(textField: searchField,placeholder: "搜索您想要的商品", fontSize: 12) { (make) in
            make.left.equalTo(bview).offset(5)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
            make.width.equalTo(bview).offset(-10)
        }
        
        let btn2 = search_bgView.drawButton(title: "搜索", titleColor: .x333333, fontSize: 13) { (make) in
            make.top.equalToSuperview().offset(6)
            make.right.equalToSuperview().offset(-10)
        }
        btn2.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        btn2.addTarget(self, action: #selector(onSearchAction(button:)), for: .touchUpInside)
        
        //画横线
        let line = headView.drawView { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(2)
        }
        line.backgroundColor = .xF2F2F2
        
//        headView.drawView { (make) in
//
//        }
        
        safeView.drawView(view: userSearchList) { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
            make.height.equalTo(330)
        }
        userSearchList.backgroundColor = .white
        userSearchList.titleLabel.text = "搜索历史"
        userSearchList.callDelBlock {
            self.delSearchHistory()
        }
        userSearchList.callMoreBlock {
            
        }
        userSearchList.tagsView.addTapGRToBoxes(callback: { (s) in
            self.searchField.text = s
            self.onSearchAction(button: UIButton())
        })
        userSearchList.callRefreshBlock {
            self.userSearchList.snp_remakeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.headView.snp.bottom)
                let hight = self.userSearchList.tagsView.height+100
                
                if hight < 330 {
                    make.height.equalTo(hight)
                    self.userSearchList.btnMore.isHidden = true
                }
                else {
                    make.height.equalTo(330)
                }
            }
            
            self.safeView.addSubview(self.hotSearchList)
            if(self.userSearchList.listAry.count == 0) {
                self.userSearchList.isHidden = true
                self.hotSearchList.snp.remakeConstraints { (make) in
                    make.left.right.equalToSuperview()
                    make.top.equalTo(self.headView.snp.bottom)
                    make.bottom.equalToSuperview()
                }
            }
            else {
                self.userSearchList.isHidden = false
                self.hotSearchList.snp.remakeConstraints { (make) in
                    make.left.right.equalToSuperview()
                    make.top.equalTo(self.userSearchList.snp.bottom)
                    make.bottom.equalToSuperview()
                }
            }
        }
        
        hotSearchList.titleLabel.text = "热门搜索"
        hotSearchList.btnDel.isHidden = true
        hotSearchList.btnMore.isHidden = true
        hotSearchList.backgroundColor = .white
        hotSearchList.callDelBlock {
            
        }
        hotSearchList.callMoreBlock {
            
        }
        hotSearchList.tagsView.addTapGRToBoxes(callback: { (s) in
            self.searchField.text = s
            self.onSearchAction(button: UIButton())
        })
        


        //添加列表
        safeView.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(33)
            make.top.equalTo(headView.snp.bottom).offset(-8)
            make.width.equalTo(74)
            make.height.equalTo(100)
        }
        // 设置边框
        tableView.layer.borderWidth = 1
        tableView.layer.borderColor = UIColor.xF2F2F2.cgColor
        tableView.isHidden = true
        tableView.backgroundColor = .white
        tableView.layer.cornerRadius = 7.0
        
        safeView.drawView(view: jView){ (make) in
            make.width.height.equalTo(10)
            make.left.top.equalTo(tableView)
        }
        jView.backgroundColor = .white
        jView.isHidden = true
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.SetBorderWithView(self.jView,top: true,left: true,bottom: false,right: false,width: 1,color: UIColor.xF2F2F2)
        }
        
        safeView.drawView(view: jView1){ (make) in
            make.width.height.equalTo(10)
            make.right.top.equalTo(tableView)
        }
        jView1.backgroundColor = .white
        jView1.isHidden = true
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.SetBorderWithView(self.jView1,top: true,left: false,bottom: false,right: true,width: 1,color: UIColor.xF2F2F2)
        }
                        
        //当点击表格行时
        tableView.onDataSelectedSubject().bindWeak(self) { (data, s) in
            s.onSelectCell(data: data)
        }
        
        //刷新相关事件绑定
        tableView.onSetCellSubject().bindWeak(self) { (cell, s) in
        }
        
        initKeyboardObserver()
        fillAccessoryToolBar()
    }
}

// MARK:- 事件
extension M_SearchPageVC {
    /// 圆角设置
    ///
    /// - Parameters:
    ///   - view: 需要设置的控件
    ///   - corner: 哪些圆角
    ///   - radii: 圆角半径
    /// - Returns: layer图层
    func configRectCorner(view: UIView, corner: UIRectCorner, radii: CGSize) -> CALayer {
        
        let maskPath = UIBezierPath.init(roundedRect: view.bounds, byRoundingCorners: corner, cornerRadii: radii)
        
        let maskLayer = CAShapeLayer.init()
        maskLayer.frame = view.bounds
        maskLayer.path = maskPath.cgPath
        
        return maskLayer
    }
    
    //部分边框
    func SetBorderWithView(_ view:UIView,top:Bool,left:Bool,bottom:Bool,right:Bool,width:CGFloat,color:UIColor)

    {
        
        if top

        {

            let layer = CALayer()

            layer.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: width)

            layer.backgroundColor = color.cgColor

            view.layer.addSublayer(layer)

        }

        if left

        {

            let layer = CALayer()

            layer.frame = CGRect(x: 0, y: 0, width: width, height: view.frame.size.height)

            layer.backgroundColor = color.cgColor

            view.layer.addSublayer(layer)

        }

        if bottom

        {

            let layer = CALayer()

            layer.frame = CGRect(x: 0, y: view.frame.size.height - width, width: view.frame.size.width, height: width)

            layer.backgroundColor = color.cgColor

            view.layer.addSublayer(layer)

        }

        if right

        {

            let layer = CALayer()

            layer.frame = CGRect(x: view.frame.size.width - width, y: 0, width: width, height: view.frame.size.height)

            layer.backgroundColor = color.cgColor

            view.layer.addSublayer(layer)

        }

    }
    
    func queryData() {
        tableView.list = zoneAry
        tableView.reloadData()
        tableView.snp.remakeConstraints { (make) in
            make.left.equalToSuperview().offset(33)
            make.top.equalTo(headView.snp.bottom).offset(-8)
            make.width.equalTo(76)
            make.height.equalTo(30*zoneAry.count)
        }
        tableView.bringSubviewToFront(userSearchList)
    }
    
    @objc func onSelAction(button:UIButton){
        tableView.isHidden = !tableView.isHidden
        jiaoView.isHidden = tableView.isHidden
        jView.isHidden = tableView.isHidden
        jView1.isHidden = tableView.isHidden
        if !tableView.isHidden {
            safeView.addSubview(tableView)
            safeView.addSubview(jView)
            safeView.addSubview(jView1)
        }
    }
    
    @objc func onSearchAction(button:UIButton){
        tableView.isHidden = true
        jiaoView.isHidden = tableView.isHidden
        jView.isHidden = tableView.isHidden
        jView1.isHidden = tableView.isHidden
        
        searchField.resignFirstResponder()
        var key = searchField.text
        if key?.count ?? 0 < 1 {
            key = searchField.placeholder
        }
        let vc = M_ProductBySearchVC(keyword: key ?? "", zoneCode: curZone!)
        pushViewController(vc)
//        vc.headTitle.text = searchField.text
    }
    
    //当点击表格行事件
    func onSelectCell(data:ZoneCodeModel){
        var name = ""
        if data.code == "105002" {
            name = "京东配送"
            self.searchField.placeholder = "搜索您想要的商品"
        }
        else {
            name = "自营"
            getSyssettingbase(callback: { (sec,data) in
                if sec {
                    self.searchField.placeholder = data.getString("proprietarySearchKeyword")
                }
                else {
                    self.searchField.placeholder = "搜索您想要的商品"
                }
            })
        }
        
        tableView.isHidden = true
        jiaoView.isHidden = tableView.isHidden
        jView.isHidden = tableView.isHidden
        jView1.isHidden = tableView.isHidden
        curZone = data
        zoneSelBtn.setTitle(name, for: .normal)
        self.userSearchList.listAry = []
        self.hotSearchList.listAry = []
        getSearchHot(page: 1, pageSize: 10)
    }
    
}




///搜索词列表
class M_SearchList: UIView {
    
    //定义一个闭包类型
    typealias delBlock = () -> Void
    //声明一个变量
    var delBtnBack: delBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callDelBlock(block: @escaping delBlock) {
        delBtnBack = block
    }
    
    //定义一个闭包类型
    typealias moreBlock = () -> Void
    //声明一个变量
    var moreBtnBack: moreBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callMoreBlock(block: @escaping moreBlock) {
        moreBtnBack = block
    }
    
    //定义一个闭包类型
    typealias refreshBlock = () -> Void
    //声明一个变量
    var refreshBtnBack: refreshBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callRefreshBlock(block: @escaping refreshBlock) {
        refreshBtnBack = block
    }
    
    let titleLabel = UILabel()
    let btnDel = Button()
    let btnMore = Button()
    let tagsView = TagFlowView()
    var listAry = [String](){
        didSet{
            tagsView.isDirty = true
            tagsView.list = listAry
            tagsView.addTextBoxes()

            if refreshBtnBack != nil {
                refreshBtnBack!()
            }
        }
    }
    
    override func draw(_ rect: CGRect) {
//        tagsView.frame = CGRect(x: 10, y: 50, width: rect.width-20, height: rect.height-80)
        tagsView.width = rect.width-20
        self.addSubview(tagsView)
        tagsView.snp_makeConstraints{ (make) in
            make.left.equalTo(10)
            make.top.equalTo(50)
            make.width.equalToSuperview().offset(-20)
            make.height.equalToSuperview().offset(-80)
        }
        
//        对tagsView进行添加和布局

        tagsView.setProp(textFont: .systemFont(ofSize: 12), textColor: .x666666, horizontalPadding: 10, lineHeight: 25+5, horizontalMargin: 5, verticalMargin: 5, cornerRadius: 15, fillColor: .xF8F8F9, borderColor: .white)
        
        drawLabel(label: titleLabel, text: titleLabel.text, fontSize: 15, fontWeight: .medium, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(20)
        }
        
        drawButton(button: btnDel,imageNamed: "shangchu_58") { (make) in
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(20)
        }
        btnDel.addTarget(self, action: #selector(onDelAction(button:)), for: .touchUpInside)
        btnDel.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        
        drawButton(button: btnMore,title: "更多搜索历史", titleColor: .x999999, fontSize: 12) { (make) in
            make.bottom.equalToSuperview().offset(-10)
            make.centerX.equalToSuperview()
        }
        btnMore.addTarget(self, action: #selector(onMoreAction(button:)), for: .touchUpInside)
        btnMore.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
    }
    
    @objc func onDelAction(button:UIButton){
        if delBtnBack != nil {
            delBtnBack!()
        }
    }
    
    @objc func onMoreAction(button:UIButton){
        if moreBtnBack != nil {
            moreBtnBack!()
        }
    }
    
    
}
